import { Component, Input, OnInit, ViewChild, EventEmitter, Output, SimpleChanges} from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd";
import { NziModalService } from "ng-zorro-iop/modal/nzi-modal.service";
import { FcsService } from "../../../../service/fcs.service";
import { CommonService } from "../../../../service/common.service";
import { ActivatedRoute, Router } from "@angular/router";

@Component({
  selector: 'app-function-layer',
  templateUrl: './function-layer.component.html',
  styleUrls: ['./function-layer.component.less']
})
export class FunctionLayerComponent implements OnInit {
	@ViewChild('bindLayerFormComponent', { static: false }) bindLayerFormComponent;
  @Input() layerData;
	@Output()  changeData = new EventEmitter<any>();
  @Input() functionId = '';
	@Input() groupId = '';
	bindLayerForm: FormGroup;
	layerList = [];
  layerNameList = [];
	layerVersionList = [];
	layerVersionSelected = [] //已选的版本

  pageSize = 10;
  pageNo = 1;
  totalCount = 0;
  isLogLoading = true;
  layerRuntime = ''; // 绑定层运行环境
	layerDescription = ''; // 绑定层描述

  disableOperation: boolean = false;
  disableOperationContent: string;
	disableAdd: boolean = false;
	disableAddContent: string;
	data;
	detailGroupId = "";
    detailFunctionId = "";
    detailVersionName = "";
	statusMonitoringInterval = null;

  constructor(private fcsService: FcsService,
		private modalService: NziModalService,
		private fb: FormBuilder,
		private commonService: CommonService,
		private activatedRoute: ActivatedRoute,
    private messageService: NzMessageService) {
			this.bindLayerForm = this.fb.group({
				layerName: [null,[Validators.required]],
				layerVersion: [null,[Validators.required]]
			})
		 }



  getLayerList() {

		this.layerList = this.layerData.layerInfos;
    if(this.layerList){
      this.layerList.forEach(i => {
			  this.layerVersionSelected.push(i.versionId)
		  });
    }
		
		// console.log(this.layerVersionSelected)
		this.getLayerByRuntime(this.layerData.runtime)
		this.isLogLoading = false;
  }
  

	createLayer(tpl) {
    this.modalService.create({
      nzTitle: '绑定层',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: tpl,
      nzOnOk: () => {
				for (const i in this.bindLayerForm.controls) {
					this.bindLayerForm.controls[i].markAsDirty();
					this.bindLayerForm.controls[i].updateValueAndValidity();
				}
				if (!this.bindLayerForm.valid) {
					return false;
				}
		
				let value = this.bindLayerFormComponent.getFormData();
				this.layerData && this.layerData.bindingLayers.push(value['layerVersion'])
				const params = {
					bindingLayers : this.layerData.bindingLayers
				};
				const messageId = this.messageService.loading('层绑定中，请稍候').messageId;
				this.fcsService.modifyFunctionLayer(this.groupId,this.functionId,params).subscribe(res => {
          this.messageService.remove(messageId);
					this.messageService.success('层绑定成功');
					this.getFunctionDetail();
					this.changeData.emit({refresh: true})
          this.resetForm()
				},error => {
					this.messageService.remove(messageId);
				})
      },
      nzOnCancel: () => {
        this.resetForm()
      }
    });
  }
  
	resetForm(): void {
		this.layerRuntime = ''; // 绑定层运行环境
	  this.layerDescription = ''; // 绑定层描述
    this.bindLayerForm.reset();
    for (const key in this.bindLayerForm.controls) {
      if (key) {
        this.bindLayerForm.controls[key].markAsPristine();
      }
    }
  }

	unBindLayer(data) {
    this.modalService.delete({
      nzTitle: '解绑层',
      nzContentTitle: `确定解绑层 <em>“${data.layerName}：${data.version}”</em> 吗？`,
      nzOnOk: () => {
				const params = {
					bindingLayers : this.layerData && this.layerData.bindingLayers.filter(v=> v !== data['versionId'])
				};
				const messageId = this.messageService.loading('层解绑中，请稍候').messageId;
				this.fcsService.modifyFunctionLayer(this.groupId,this.functionId,params).subscribe(res => {
					this.messageService.remove(messageId);
					this.messageService.success('层解绑成功');
					this.getFunctionDetail();
					this.changeData.emit({refresh: true})
				},
				error => {
					this.messageService.remove(messageId);
				})
      },
      nzCancelText: '取消',
      nzOnCancel: () => { },
    });
  }

	getLayerByRuntime(data){
		this.fcsService.getLayerByRuntime(data).subscribe(res => {
			if(res){
				this.layerNameList = res; // 层名称列表
				this.layerVersionList = res[0].versions; // 层版本列表	
			}
		})
	}

	changeLayerList(val){
		if(val){
			// this.layerVersionList = this.layerNameList.filter(v=>v.layerId === val)[0].versions;
			this.layerVersionList = this.layerNameList.filter(v => v.layerId === val)[0].versions.filter(i=>!(this.layerVersionSelected.includes(i.versionId)))
		}
	}

  changeLayerVersion(val){
		if(val){
			this.layerRuntime = this.layerVersionList.filter(v=>v.versionId === val)[0].runtimes;
			this.layerDescription = this.layerVersionList.filter(v=>v.versionId === val)[0].description;
		}
	}
	ngOnInit() {
		this.isLogLoading = true;
    this.getLayerList();



	this.detailGroupId = this.activatedRoute.snapshot.params["groupId"];
    this.detailFunctionId = this.activatedRoute.snapshot.params["functionId"];
    this.detailVersionName = this.activatedRoute.snapshot.params['versionName'];
	this.getFunctionDetail();
  }
	ngOnChanges(simpleChanges: SimpleChanges) {
    if (simpleChanges.layerData) {
			this.isLogLoading = true;
			this.getLayerList();
    }
  }
  ngOnDestroy() {
    this.doClearInterval();
  }

  doClearInterval() {
    clearInterval(this.statusMonitoringInterval);
    this.statusMonitoringInterval = null;
  }

  getFunctionDetailForStatus() {
    this.fcsService.getFunctionDetail(this.detailGroupId, this.detailFunctionId, this.detailVersionName).subscribe(res => {
      res['envs'] = '';
      this.data = res;
      
      this.checkButtonStatus();
    }, err => {
    });
  }





  getFunctionDetail() {
    
    this.fcsService.getFunctionDetail(this.detailGroupId, this.detailFunctionId, this.detailVersionName).subscribe(res => {
    
      res['envs'] = '';
      this.data = res;
      this.checkButtonStatus();
	  if (res && res.status) {
        let needMonitoring = (res.status === 'creating' || res.status === 'updating');
        if (needMonitoring) {
          if (!this.statusMonitoringInterval) {
            this.statusMonitoringInterval = setInterval(() => {
              this.getFunctionDetailForStatus();
            }, 5000);
          }
        } else {
			if(this.data.bindingLayers.length === 5){
				this.disableAdd = true;
				this.disableAddContent = '当前绑定层个数最大为5个';
			  }
          clearInterval(this.statusMonitoringInterval);
        }
      }
    }, error => {
      this.data = null;
    })
  }




  checkButtonStatus() {
    this.commonService.translateRuntime(this.data);
    if (this.data) {
      if (this.data.status === 'updating' || this.data.status === 'creating' ) {
        this.disableAdd = true;
       
          if (this.data.status === 'creating') {
            this.disableAddContent = '当前函数正在创建中，不支持绑定';
          } else if (this.data.status === 'updating') {
            this.disableAddContent = '当前函数正在更新中，不支持绑定';
          }
        
      } else {
		
        this.disableAdd = false;
		if(this.data.bindingLayers.length === 5){
			this.disableAdd = true;
			this.disableAddContent = '当前绑定层个数最大为5个';
		  }
      }
      if (this.data.status === 'updating' || this.data.status === 'creating') {
        this.disableOperation = true;
        if (this.data.status === 'creating') {
          this.disableOperationContent = '当前函数正在创建中，不支持操作';
        } else if (this.data.status === 'updating') {
          this.disableOperationContent = '当前函数正在更新中，不支持操作';
        }
      } else {
        // 只清理一次即可
        this.doClearInterval();
        this.disableOperation = false;
      }
    }
  }
}
